import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:im_app/im/page/bloc/SessionListCubit.dart';
import 'package:im_app/im/util/DbUtil.dart';
import 'package:im_app/im/util/ImSingleton.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

import '../../../../dao/ImSessionDao.dart';
import '../../../../pojo/ImPojo.dart';
import '../../../../util/ImConstant.dart';
import '../../ListSeparator.dart';
import '../UserIconView.dart';

class UserItemView extends StatelessWidget {

  final _logger = Logger(
    printer: PrettyPrinter(),
  );

  final ImUser imUser;
  final ImUser? preUser;

  UserItemView(this.imUser, this.preUser);

  @override
  Widget build(BuildContext context) {
    if (this.preUser == null || this.imUser.firstLetter != this.preUser?.firstLetter ) {
      return Column(
        children: [
          _buildGroupTitle(),
          _buildUser(context),
          Padding(padding: EdgeInsets.only(top: 5, bottom: 5), child: ListSeparator(),),
        ],
      );
    }
    return Column(
        children: [
          _buildUser(context),
          Padding(padding: EdgeInsets.only(top: 5, bottom: 5), child: ListSeparator(),),
        ],
    );
  }

  Widget _buildUser(BuildContext context) {
    return ListTile(
        dense: true,
        leading: UserIconView(user: imUser, iconSize: ImConstant.IM_USER_ICON_SIZE - 10,),
        title: Text("${imUser?.userName??''}",
            style: const TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w300)),
        onTap: () {
          _showSendMessage(context, imUser);
        }
    );
  }

  Widget _buildGroupTitle(){
    return Container(
      color: Colors.grey.shade300,
      padding: const EdgeInsets.only(left: 10),
      child: Row(children: [
        Text(imUser.firstLetter??"".toUpperCase(), style: const TextStyle(fontSize: 16),)
      ],),
    );
  }

  void _showSendMessage(BuildContext context, ImUser imUser) async {
    _logger.i("show userId: ${imUser.userId}");
    var userId = await ImSingleton.getInstance().session.userId;

    var sessionDao = ImSessionDao();
    var imSession = await sessionDao.getByUserId(userId!, userId, imUser.userId);
    if (imSession == null) {
      imSession = ImSession.buildWithUser(userId, imUser);
      await sessionDao.insert(imSession);
    }

    SessionListCubit sessionListCubit = context.read<SessionListCubit>();
    sessionListCubit.addSession(imSession);

    Navigator.of(context).pushNamedAndRemoveUntil("/MessageSendPage", ModalRoute.withName('/MainPage'), arguments: {"id": imSession?.id!, "name": imSession?.name});
  }
}